package com.hc.comm.interceptor;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.hc.comm.utils.StringUtil;

public class AbsolutelyPathInterceptor extends HandlerInterceptorAdapter {

	private static final String HTTPS_PROTOCOL = "http://";
	public static final String ABSOLUTE_CONTEXT_PATH_NAME = "absoluteContextPath";

	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		if (request != null) {
			String absoluteContextPath;
			if (request.getServerPort() == 80) {
				absoluteContextPath = HTTPS_PROTOCOL + request.getServerName()
						+ request.getContextPath();
			} else {
				absoluteContextPath = HTTPS_PROTOCOL + request.getServerName()
						+ ":" + request.getServerPort()
						+ request.getContextPath();
			}
			
			request.setAttribute(ABSOLUTE_CONTEXT_PATH_NAME,
					absoluteContextPath);
			request.setAttribute("jsessionid", request.getSession().getId());
			request.getSession().setAttribute(ABSOLUTE_CONTEXT_PATH_NAME,
					request.getSession().getId());
			request.getSession()
					.setAttribute("jsessionid", absoluteContextPath);
		}
		return super.preHandle(request, response, handler);
	}

	@Override
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		// absoluteContextPath in request may be missing if request redirected
		if (modelAndView != null
				&& StringUtil.isNotEmpty((String) request
						.getAttribute(ABSOLUTE_CONTEXT_PATH_NAME))) {
			modelAndView.addObject(ABSOLUTE_CONTEXT_PATH_NAME,
					request.getAttribute(ABSOLUTE_CONTEXT_PATH_NAME));
		}

		super.postHandle(request, response, handler, modelAndView);
	}

}
